<template>
	<view style="position: relative;">
		<view class="ut-indexed-search ">
			<slot name="left-icon" />
			<uni-search-bar
				v-model="searchValue"
				radius="20"
				clearButton="auto"
				:placeholder="$t('app.keywords')"
				@focus="onFocus"
				@cancel="onCancelSearch"
				@input="onSearch"
			/>
			<slot name="right-icon" />
		</view>
		<!-- <uni-nav-bar leftWidth="0" rightWidth="60rpx" backgroundColor="#EA0D2C" rightIcon="plusempty" color="#FFF">
      <view class="input-view">
        <uni-icons
          class="input-uni-icon"
          type="search"
          size="18"
          color="#999"
        />
        <input
          confirm-type="search"
          class="nav-bar-input"
          type="text"
          :placeholder="$t('app.keywords')"
          @focus="onFocus"
				@cancel="onCancelSearch"
				@input="onSearch"
        />
      </view>
      
    </uni-nav-bar> -->
		<view
			class="ut-indexed-wrapper"
			:class="{
				'ut-indexed-search-wrapper': isSearch && isEmpty(dataList),
				'ut-contact-query': isQuery && !isSearch,
				'ut-contact-query-search': isQuery && isSearch,
			}"
		>
			<scroll-view
				v-if="!isEmpty(dataList)"
				:scroll-into-view="scrollIntoView"
				scroll-y
				scroll-with-animation
				class="ut-indexed-scroll-view"
		>
				<view v-for="(itemList, key, idx) in dataList" :key="key" class="ut-indexed-item" :id="key === '#' ? 'ut' : key">
					<su-sticky v-if="!isSearch" :customNavHeight="0" :index="key" :id="key">
						<view class="ut-indexed-section" style="background-color: #eee;">{{ key }}</view>
					</su-sticky>
					<uni-swipe-action ref="xswipe">
						<uni-swipe-action-item
							v-for="item in itemList"
							:key="item"
							:right-options="options"
							:disabled="!swiperEnable"
							@click="e => onClick(e, item, idx)"
							@change="onChange"
						>
							<view style="display: flex; align-items: center;">
								<view class="ut-select-icon" style="display: flex; margin-left: 8rpx; ">
									<radio
										v-if="isQuery"
										:checked="item.isSelected"
										activeBorderColor="#EA0D2C"
										activeBackgroundColor="#EA0D2C"
										@click="onCheckboxed(item)"
									/>
								</view>
								<slot name="content" :data="item" />
								<view v-if="!$slots.content" style="height: 42px; padding: 6px;">
									<view>{{ item[nameField] }}</view>
								</view>
							</view>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</view>
			</scroll-view>
			<view v-if="isEmpty(data) || (searchValue && isEmpty(dataList))">
				<!-- <s-empty
					icon="/static/data-empty.png"
					:text="$t('app.empty')"
				/> -->
			</view>
			<view v-if="!isSearch && !isEmpty(dataList)" class="ut-indexed-right">
				<view
					v-for="letter in rightStepList"
					:key="letter.name"
					:class="{ 'ut-indexed-select': letter.isSelected }"
					class="ut-indexed-right--item"
					@tap="onSelected(letter)"
				>
					{{ letter.name }}
				</view>
			</view>
		</view>
		<view v-if="isQuery && multiple" class="ut-select-wrapper">
			<view class="ut-select-item">
				<view v-for="item in selectItems" :key="item.id" class="ut-select--item">
					<image :src="item.pic"></image>
					<view class="ut-select-name">{{ item[nameField] }}</view>
				</view>
			</view>
			<button
				class="ss-reset-button ut-main-theme ut-selected-btn"
				style="margin: 0;"
			>
			{{ $t("btn.confirm") }}
		</button>
		</view>
		<view v-if="isQuery && !multiple" class="ut-single-button">
			<button
				class="ss-reset-button ut-main-theme ut-selected-btn"
				style="margin: 0;"
				@tap="onQueryConfirm"
			>
			{{ $t("btn.confirm") }}
		</button>
		</view>
	</view>
</template>

<script setup>
/**
 * 通讯录索引 - nt-indexed
 *
 * property {Array} data 										- 数据源
 * property {String} nameField 								- 名称字段值
 * property {Boolean} swiperEnable 						- 是否可滑动
 * property {Array} options										- 滑动按钮选项
 * property {Array} keywords									- 查询关键字段
 *
 * @slot content															- 自定义label样式
 *
 */
import { ref, nextTick } from "vue"
import { onLoad } from '@dcloudio/uni-app';
import { clone, groupBy, isEmpty, orderBy } from "xe-utils";
import pinyin from './pinyin.js'

const props = defineProps({
	data: {
		type: Array,
		default() {return []},
	},
	options: {
		type: Array,
		default() { return [] },
	},
	nameField: {
		type: String,
		default: 'name'
	},
	backgroundColor: {
		type: String,
		default: '#EA0D2C'
	},
	swiperEnable: {
		type: Boolean,
		default: true
	},
	showRightButton: {
		type: Boolean,
		default: false
	},
	isQuery: {
		type: Boolean,
		default: false
	},
	multiple: {
		type: Boolean,
		default: false
	},
	keywords: {
		type: Array,
		default() { return ['name'] },
	}
});


// 创建pinyin实例
const pinyinInstance = new pinyin({charCase:0})
// 复制信息用于查询
let copyData = clone(props.data, true)
let copyDataList = {}

const xswipe = ref(null)
const searchValue = ref('')
const scrollIntoView = ref('')
const rightStepList = ref({})
const dataList = ref({})
const isSearch = ref(false)
const tabbarH = ref(0)
const selectItems = ref([])

/**
 * 打开查询界面
 */
const onFocus = () => {
	searchValue.value = ""
	copyDataList = clone(dataList.value, true)
	dataList.value = {}
	isSearch.value = true
}

const onSearch = val => {
	if (val) {
		const searchList = copyData.filter(f => f.keyWords.includes(val))
		dataList.value = searchList.length ? { result: searchList } : { result: [] }
	} else {
		dataList.value = {}
	}
}
/** 取消查询 */
const onCancelSearch = () => {
	isSearch.value = false
	searchValue.value = null
	nextTick(() => {
		dataList.value = clone(copyDataList, true)
	})
	console.log(dataList.value, isEmpty(dataList.value))
}
/** 右侧索引点击 */
const onSelected = letter => {
	console.log(letter)
	rightStepList.value.forEach(_ => {
		_.isSelected = letter.name === _.name
	})
	scrollIntoView.value = letter.name === "#" ? "ut" : letter.name
}
/** 右滑按钮点击 */
const onClick = (e, item, idx) => {
	console.log('e===', e)
	xswipe.value[idx].closeAll()
	emits('buttonTap', item, e.index)
}
/** 插槽内容点击 */
const onSlotTap = item => {
	props.isQuery && onCheckboxed(item)
}
/** 勾选数据 */
const onCheckboxed = item => {
	Object.keys(dataList.value).forEach((key) => {
		dataList.value[key].forEach(_ => {
			_.isSelected = _.id === item.id
		})
	})
	if (props.multiple) {
		const idx = selectItems.value.findIndex(s => s.id !== item.id)
		if (item.isSelected) {
			idx === -1 && selectItems.value.push(item)
		} else {
			idx !== -1 && selectItems.value.splice(idx, 1)
		}
	} else {
		selectItems.value = [item]
	}
}
const onQueryConfirm = () => {
	emits('selected', selectItems.value)
}
// 展开事件
const onChange = (e) => {
	emits('change', e)
}
// const reload = () => {
// 	copyData = clone(props.data, true)
// 	console.log(props.data)
// 	let keywords = null
// 	copyData.forEach(data => {
// 		const py = pinyinInstance.getCamelChars(data[props.nameField].trim())
// 		let letter = py.charAt(0).toLocaleUpperCase()
// 		letter = /^[a-zA-Z]$/.test(letter) ? letter : "#"
// 		data.letterId = letter
// 		keywords = null
// 		props.keywords.forEach(key => {
// 			keywords = keywords ? `${`${keywords}`}-${data[key]}` : `${data[key]}`
// 		})
// 		data.keyWords = keywords
// 	})
// 	dataList.value = groupBy(orderBy(copyData, 'letterId'), 'letterId')
// }
// 数据处理
const initData = () => {
	const letterSet = new Set()
	let keywords = null
	copyData.forEach(data => {
		const py = pinyinInstance.getCamelChars(data[props.nameField].trim())
		let letter = py.charAt(0).toLocaleUpperCase()
		letter = /^[a-zA-Z]$/.test(letter) ? letter : "#"
		letterSet.add(letter)
		data.letterId = letter
		keywords = null
		props.keywords.forEach(key => {
			keywords = keywords ? `${`${keywords}`}-${data[key]}` : `${data[key]}`
		})
		data.keyWords = keywords
	})
	dataList.value = groupBy(orderBy(copyData, 'letterId'), 'letterId')

	rightStepList.value = orderBy(Array.from(letterSet)).map(m => {
		return { name: m, isSelected: false }
	})
}

const emits = defineEmits(['buttonTap', 'change', "selected"])

onLoad(() => {
	isSearch.value = false
	initData()
	console.log(uni.getSystemInfoSync())
	// const deviceType = uni.getSystemInfoSync().platform.deviceType
	// tabbarH.value = deviceType === 'pad' ? '170rpx' : uni.getSystemInfoSync().platform === 'ios' ? '370rpx' : '252rpx'
	// if (uni.getSystemInfoSync().screenHeight === 667) {
	// 	tabbarH.value = "242rpx"
	// }
	tabbarH.value = uni.getSystemInfoSync().windowBottom * 2 + 'px'
	console.log(tabbarH.value)
})

defineExpose({ onSlotTap })

</script>
<style>
	v-deep ::-webkit-scrollbar {
		width: 0;
		height: 0;
		color: transparent;
		display: none;
	}
</style>
<style lang="scss" scoped>
.ut-indexed-search {
	display: flex;
	align-items: center;
	background-color: v-bind(backgroundColor);
	:deep() {
		.uni-searchbar {
			flex: 1;
			.uni-searchbar__cancel {
				color: #FFF;
			}
		}
	}

}
.uni-searchbar__cancel {
	color: #FFF;
}
.ut-indexed-wrapper {
	// height: calc(100vh - v-bind(tabbarH));
	height: 100%;   
	display: flex;
	justify-content: center;
	align-items: self-start;
	.ut-indexed-scroll-view {
		overflow: hidden;
		height: 100%;
	}

	.ut-indexed-section {
		padding: 6rpx 16rpx;
	}

	.ut-indexed-right {
		color: #666;
		padding: 0 4rpx;
		align-self: center;
		flex-direction: column;
    font-size: 24rpx;
    font-weight: 500;
		.ut-indexed-right--item {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 36rpx;
			width: 36rpx;
			border-radius: 25%;
		}
		.ut-indexed-select {
			background-color: #ff6a0d;
			color: #FFF;
		}
	}
}
.ut-indexed-search-wrapper {
	height: calc(100vh - 212rpx);
	background-color: rgba($color: #000000, $alpha: 0.12);
}
// 查询界面高度
.ut-contact-query {
	height: calc(100vh - 235rpx);
}
// 
.ut-contact-query-search {
	height: calc(100vh - 235rpx);
}
.ut-index-search-content {
	background-color: #FFF;
	height: calc(100vh - 110rpx);
	overflow: auto;
}

.ut-select-wrapper {
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;
	padding: 12rpx 6rpx;
	.ut-select-item {
		display: flex;
		width: 80%;
		.ut-select--item {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
		}
		image {
			height: 60rpx;
			width: 60rpx;
		}
		.ut-select-name {
			font-size: 22rpx;
		}
	}
	.ut-selected-btn {
		width: 150rpx;
	}
}
.ut-single-button{
	display: flex;
	align-items: center;
	width: 100%;
	padding: 24rpx;
	box-sizing: border-box;
	border-top: 1px solid #dadada;
	button {
		width: 100%;
	}
}
</style>